package utility;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import model.tiles.AbstractTile;
import model.tiles.EarthTile;
import model.tiles.WaterTile;
import model.tiles.GrassTile;
import model.tiles.LadderTile;
import model.tiles.SurfaceTile;

public class Utility {
	
	/**
	 * readMapFile reads a file of a map and returns that map in form of an array of tiles
	 * @param file
	 * @return Tile[][] or null
	 */
	public static AbstractTile[][] readMapFile(File file){
		try{
			Scanner sc = new Scanner(file);
			int lines=0;
			int maxLength=0;
			while(sc.hasNextLine()){
				lines++;
				int rowLength = sc.nextLine().length();
				if(rowLength>maxLength)
					maxLength=rowLength;
			}
			sc = new Scanner(file);
			AbstractTile[][] tiles = new AbstractTile[maxLength][lines];
			for(int i=0; i<lines; i++){
				String row = sc.nextLine();
				for(int j=0; j<row.length(); j++){
					if(row.charAt(j) == 'e'){
						if(i == 0)
							tiles[j][i] = new GrassTile();
						else {
							if(tiles[j][i-1] == null || tiles[j][i-1] instanceof LadderTile)
								tiles[j][i] = new GrassTile();
							else
								tiles[j][i] = new EarthTile();
						}
					}
					if(row.charAt(j) == 'w'){
						if(j == 0)
							tiles[j][i] = new SurfaceTile();
						else {
							if(tiles[j][i-1] == null || tiles[j][i-1] instanceof LadderTile)
								tiles[j][i] = new SurfaceTile();
							else
								tiles[j][i] = new WaterTile();
						}
					}
					if(row.charAt(j) == 'l'){
						tiles[j][i] = new LadderTile();
					}
				}
			}
			return tiles;
		}
		catch(IOException e){
			return null;
		}
	}

}
